;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Merchant.Company", [])
        .controller("CompanyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, UserContextService) {
            $scope.activeFlag = [true, false, false];
            $scope.markInfo = {
                allChecked: false,
                curRow: 0
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.detailInfo = {
                isSap:0,
                isBarcode:0,
                isReturnAudit:1,
                outsideFlag:0,
                factoryId: 'G1'
            };

            $scope.factoryList = [];
            $scope.factoryMap = {};

            $scope.companyTypeList = [];
            $scope.companyTypeMap = {};

            $scope.moduleTemplate = [];

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/company/export"),
                sectionParam: {companyIds: []},
                allUrl: ybHttp.RequestUrl("device", "/company/exportAll")
            };
            
            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            $scope.tableConfig = {
                fixedWidth: 120,
                scrollWidth: 1200,
                tableCol: [
                    {
                        name: "企业代码",
                        dataField: "supplierNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "企业名称",
                        dataField: "companyName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "组织机构代码",
                        dataField: "orgCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "供货工厂",
                        dataField: "factoryName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "企业类型",
                        dataField: "companyTypeDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "渠道",
                        dataField: "channelDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "登录账号",
                        dataField: "orgId",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "默认密码",
                        dataField: "defaultPass",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "权限模板",
                        dataField: "templateName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        dataField: "",
                        name: "操作",
                        width: 120,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            var btnPermissionCode = {
                companyAdd: window.ActionCode.companyAdd,
                companyEdit: window.ActionCode.companyEdit,
                companyDel: window.ActionCode.companyDel,
                companyExport: window.ActionCode.companyExport
            };

            $scope.btnPermission = {
                companyAdd: true,
                companyEdit: true,
                companyDel: true,
                companyExport: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function getDictionaryList(dictKey, dataType) {
                ybWidget.GetDictionaryMap(dictKey).then(function (data) {
                    if (data.code !== 0) {
                        ybWidget.ShowMessage(data, MESG_TYPE.Error);
                        return false;
                    }
                    $scope[dataType+'List'] = data.value;
                    angular.forEach(data.value,function (item) {
                        $scope[dataType+'Map'][item.code] = item.name;
                    });
                })
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"}};
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        getScepter();
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    isSap:0,
                    isBarcode:0,
                    isReturnAudit:1,
                    factoryId: 'G1'
                };
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: 0
                };
                var service = "device";
                var reqUrl = "/company/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.defaultPass = 'SgcX!515';
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show"+ toolbar]) {
                    $scope.toolbarConfig["show"+ toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show"+ toolbar] = true;
                    });
                }
            };
            
            function getScepter() {
                var service = "auth";
                var reqUrl = "/template/list";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.moduleTemplate = resp.value;
                });
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.delData = function (delType, Id) {
                var service = "device";
                var reqUrl = "/company/delete";
                var param = {};
                param.orgIds = [];

                if (delType === "single") {
                    param.orgIds.push(Id);
                }

                if (delType === "batch") {
                    for (let item of $scope.dataList) {
                        if (!!item.isChecked && item.companyType!=='1') {
                            param.orgIds.push(item.orgId);
                        }
                    }
                    if (param.orgIds.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }

                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param.orgIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            function getDetail(service, reqUrl, param) {
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            function checkAll() {
                var selectAllFlag = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }
            function getCompanyIds() {
                $scope.exportParam.sectionParam.companyIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.companyIds.push(item.orgId);
                    }
                });
            };
            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                getCompanyIds();
            };

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getCompanyIds();
            };
            
            $scope.editData = function (item) {
                var service = "device";
                var reqUrl = "/company/info";
                var param = {};
                param.orgId = item.orgId;
                getDetail(service, reqUrl, param).then(function (data) {
                    if (!data) return;
                    
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(1);
                    if(!$scope.companyTypeMap[data.companyType]){
                        data.companyType = null;
                    }
                    $scope.detailInfo = data;
                });
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/company/add";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/company/update";
                }
                $scope.detailInfo.factoryName = $scope.factoryMap[$scope.detailInfo.factoryId]
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.selectGPSinfo = function () {
                const options = {
                    title: '供应商',
                    service: 'sync',
                    url: '/supplier/list',
                    keyWords: [{label: '供应商代码', field: 'supplierNoLike'}, {label: '供应商名称', field: 'supplierNameLike'}],
                    fields: [
                        {
                            name: '供应商代码',
                            dataField: 'supplierNo',
                            width: "40%"
                        },
                        {
                            name: '供应商名称',
                            dataField: 'supplierName',
                            width: "60%"
                        },
                    ]
                }
                ybWidget.DataSelector(options).then(function (data) {
                    $scope.detailInfo.companyName = data.supplierName;
                    $scope.detailInfo.supplierNo = data.supplierNo;
                    $scope.detailInfo.loginId = data.loginId;
                })
            };

            $scope.clearGPSinfo = function() {
                $scope.detailInfo.companyName = '';
                $scope.detailInfo.supplierNo = '';
                $scope.detailInfo.loginId = '';
            };

            (function () {
                getDataList();
                getDictionaryList('QYLX', 'companyType');
                getDictionaryList('SSHGCH', 'factory');
                $scope.setFixedWidth();
                setBtnPermission();
            })();
        }])
    ;
})(window, window.angular);